package vikaa.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import vikaa.bean.Formatted_address;
import vikaa.bean.SItude;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;

public class LocationUtil {
	
	public static SItude getAltitudeByGPS(Context context) throws Exception{
		SItude itude = new SItude();
		LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
		Location l = lm.getLastKnownLocation(lm.getBestProvider(getCriteria(), true));
		try{
			itude.latitude = String.valueOf(l.getLatitude());
			itude.longitude = String.valueOf(l.getLongitude());
			return itude;
		}catch(Exception e){
			return null;
		}
	}
	private static Criteria getCriteria(){
		Criteria c = new Criteria();
		c.setAccuracy(Criteria.ACCURACY_COARSE);
		c.setAltitudeRequired(false);
		c.setBearingRequired(false);
		c.setCostAllowed(false);
		c.setPowerRequirement(Criteria.POWER_LOW);
		c.setSpeedRequired(false);
		return c;
	}
	public static  SItude getAltitudeByBase(Context context) throws Exception{
		SItude itude = new SItude();
		TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		GsmCellLocation gsmLocation = (GsmCellLocation)tm.getCellLocation();
		if(gsmLocation == null)
			throw new Exception("获取基站信息失败");
		
		String operator = tm.getNetworkOperator();
		int mcc = Integer.parseInt(operator.substring(0, 3));
		int mnc = Integer.parseInt(operator.substring(3));
		int cid = gsmLocation.getCid();
		int lac = gsmLocation.getLac();
		
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://www.google.com/loc/json");
		try{
			/** 构造POST的JSON数据 */
			JSONObject holder = new JSONObject();
			holder.put("version", "1.1.0");
			holder.put("host", "maps.google.com");
			holder.put("address_language", "zh_CN");
			holder.put("request_address", true);
			holder.put("radio_type", "gsm");
			holder.put("carrier", android.os.Build.MODEL);

			JSONObject tower = new JSONObject();
			tower.put("mobile_country_code", mcc);
			tower.put("mobile_network_code", mnc);
			tower.put("cell_id", cid);
			tower.put("location_area_code", lac);

			JSONArray towerarray = new JSONArray();
			towerarray.put(tower);
			holder.put("cell_towers", towerarray);
			
			StringEntity entity = new StringEntity(holder.toString());
			post.setEntity(entity);
			
			/** 发出POST数据并获取返回数据 */
			HttpResponse response = client.execute(post);
			HttpEntity httpentity = response.getEntity();
			BufferedReader buffReader = new BufferedReader(
					new InputStreamReader(httpentity.getContent()));
			StringBuffer strBuff = new StringBuffer();
			String result = null;
			while ((result = buffReader.readLine()) != null) {
				strBuff.append(result);
			}
				/** 解析返回的JSON数据获得经纬度 */
			JSONObject json = new JSONObject(strBuff.toString());
			JSONObject subjson = new JSONObject(json.getString("location"));
			itude.latitude = subjson.getString("latitude");
			itude.longitude = subjson.getString("longitude");
		} catch (IOException e){
			throw new Exception("网络异常");
		} catch (Exception e) {
			throw new Exception("获取经纬度出现错误");
		} finally {
			post.abort();
			client = null;
		}
		return itude;
	}
	public static Formatted_address getCityByGoogleMap(SItude itude) throws Exception{
		Formatted_address fa = new Formatted_address();
		String resultString = "";
		String url = String.format(
				"http://maps.google.com/maps/api/geocode/json?latlng=%s,%s&language=zh-CN&sensor=true",
				itude.latitude, itude.longitude);
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		try {
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			BufferedReader buffReader = new BufferedReader(
					new InputStreamReader(entity.getContent()));
			StringBuffer strBuff = new StringBuffer();
			String result = null;
			while ((result = buffReader.readLine()) != null) {
				strBuff.append(result);
			}
			resultString = strBuff.toString();
			if(!StringUtils.isEmpty(resultString)){
				JSONObject jsonObj = new JSONObject(resultString);
				JSONArray resultarray = jsonObj.getJSONArray("results");
				fa.setRoute(resultarray.getJSONObject(0).getString("formatted_address")) ;
				fa.setSublocality(resultarray.getJSONObject(1).getString("formatted_address"));
				fa.setLocality(resultarray.getJSONObject(2).getString("formatted_address"));
				fa.setAdministrative_area_level_1(resultarray.getJSONObject(3).getString("formatted_address"));
				fa.setCountry(resultarray.getJSONObject(4).getString("formatted_address"));
			}
		} catch (IOException e){
			throw new Exception("网络异常");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			get.abort();
			client = null;
		}
		return fa;
	}
}
